package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WatchThreadEventHandler {
	public static void main(String[] args) throws IOException, InterruptedException {
		final Path path = Paths.get("E:/Copy");
		Map<Thread, Path> threads = new HashMap<>();
		try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
			path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
					StandardWatchEventKinds.ENTRY_DELETE);
			while (true) {
				final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);
				if (key != null) {
					for (WatchEvent<?> watchEvent : key.pollEvents()) {
						final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
						final Path filename = watchEventPath.context();
						final WatchEvent.Kind<?> kind = watchEvent.kind();
						if (kind == StandardWatchEventKinds.OVERFLOW) {
							continue;
						}
						if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
							System.out.println("发送文件去输出 -> " + filename);
							Runnable task = new Print(path.resolve(filename));
							Thread worker = new Thread(task);
							worker.setName(path.resolve(filename).toString());
							threads.put(worker, path.resolve(filename));
							worker.start();
						}

						if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
							System.out.println(filename + " 成功输出!");
						}
					}
					boolean valid = key.reset();
					if (!valid) {
						threads.clear();
						break;
					}
				}

				if (!threads.isEmpty()) {
					for (Iterator<Map.Entry<Thread, Path>> it = threads.entrySet()
							.iterator(); it.hasNext(); ) {
						Map.Entry<Thread, Path> entry = it.next();
						if (entry.getKey().getState() == Thread.State.TERMINATED) {
							Files.deleteIfExists(entry.getValue());
							it.remove();
						}
					}
				}
			}
		}
	}
}

class Print implements Runnable {
	private Path doc;

	Print(Path doc) {
		this.doc = doc;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(200);
			System.out.println("输出: " + doc);
		} catch (InterruptedException ex) {
			System.err.println(ex);
		}
	}
}
